package com.kids.englishsong.view;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.bzydroid.network.http.NetworkResponse;
import com.bzydroid.network.http.client.BzydroidHttpClient;
import com.bzydroid.network.http.exception.BzydroidNetworkExeception;
import com.bzydroid.network.http.response.HttpJSONObjectResponse;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdView;
import com.ironsource.mobilcore.CallbackResponse;
import com.ironsource.mobilcore.MobileCore;
import com.ironsource.mobilcore.MobileCore.LOG_TYPE;
import com.kids.englishsong.E4KidsConfig;
import com.kids.englishsong.E4KidsSlidingMenuActivity;
import com.kids.englishsong.adapter.ItemVideoRelativeAdapterPlay;
import com.kids.englishsong.adapter.ItemVideoRelativeAdapterPlay.IClickItemVideo;
import com.kids.englishsong.customize.BaseRequestHandler;
import com.kids.englishsong.entity.InfoVideo;
import com.kids.englishsong.service.RequestService;
import com.kids.englishsong.util.Debug;
import com.kids.englishsong.util.Util;
import com.kidstv.disneyshows.R;

public class SearchResultActivity extends E4KidsSlidingMenuActivity implements
		OnClickListener {
	private ListView lvVideo;
	private LinearLayout llLoading;
	private LinearLayout llNotInternet;
	private ItemVideoRelativeAdapterPlay adapter;

	private boolean isLoading;
	private RequestVideoNew requestVideoNew;

	private int page = 1;

	private ImageView ivABCancelSearch;
	private ImageView ivABSearch;
	private EditText edtABSearch;
	private LinearLayout llContainEdt;
	private TextView tvABTitle;
	private LinearLayout llLoadingFooter;
	private ImageView ivShare;

	private String keyword;
	private TextView tvNoData;
	private ImageView ivABLogo;
	private AdView adView;
	private RelativeLayout rlContainAds;

	@Override
	public void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		this.setContentView(R.layout.activity_list_relative);
		this.setBehindContentView(R.layout.frame_layout_container);
		// this.getSlidingMenu().setSecondaryMenu(R.layout.frame_right_container);
		this.setDefaultBar();
		configLeftSlideMenu();
		// this.removeSlidingMenu();

		init();
	}

	private void init() {
		adView = (AdView) findViewById(R.id.ad);
		rlContainAds = (RelativeLayout) findViewById(R.id.rlContainAds);
		adView.setAdListener(new AdListener() {
			@Override
			public void onReceiveAd(Ad arg0) {
				Debug.debug("onReceiveAd");

				if (adView.getVisibility() == View.VISIBLE) {
					rlContainAds.setVisibility(View.VISIBLE);
				} else {
					rlContainAds.setVisibility(View.GONE);
				}
			}

			@Override
			public void onPresentScreen(Ad arg0) {
				Debug.debug("onPresentScreen");
			}

			@Override
			public void onLeaveApplication(Ad arg0) {
				Debug.debug("onLeaveApplication");
			}

			@Override
			public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
				Debug.debug("onFailedToReceiveAd");
			}

			@Override
			public void onDismissScreen(Ad arg0) {
				Debug.debug("onDismissScreen");
			}
		});
		if (getIntent().getExtras() != null) {
			keyword = getIntent().getExtras().getString(
					E4KidsConfig.KEY_INTENT_SEARCH);
		}

		ivABCancelSearch = actionBar.getIvABCancelSearch();
		ivABSearch = actionBar.getIvABSearch();
		edtABSearch = actionBar.getEdtABSearch();
		llContainEdt = actionBar.getLlContainEdt();
		ivABLogo = actionBar.getIvABLogo();
		tvABTitle = actionBar.getTvABTitle();
		ivShare = actionBar.getIvShare();

		ivShare.setVisibility(View.GONE);

		llContainEdt.setVisibility(View.VISIBLE);
		ivABSearch.setVisibility(View.GONE);
		edtABSearch.setText(keyword);
		tvABTitle.setVisibility(View.GONE);

		ivABLogo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				onBackPressed();
			}
		});

		// edtABSearch.setOnEditorActionListener(searchAction);
		ivABSearch.setOnClickListener(this);
		ivABCancelSearch.setOnClickListener(this);

		edtABSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		edtABSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView arg0, int actionID,
					KeyEvent arg2) {
				keyword = edtABSearch.getText().toString().trim();
				if (!keyword.equals("") || !TextUtils.isEmpty(keyword)) {
					tvNoData.setVisibility(View.GONE);
					llLoading.setVisibility(View.VISIBLE);
					lvVideo.setVisibility(View.GONE);
					adapter = new ItemVideoRelativeAdapterPlay(
							SearchResultActivity.this, imageLoader, options);
					page = 1;
					loadMore();

					lvVideo.setAdapter(adapter);
				}
				return true;
			}
		});

		lvVideo = (ListView) findViewById(R.id.lvRelative);

		tvNoData = (TextView) findViewById(R.id.tvNoData);

		LayoutInflater inflater = getLayoutInflater();
		View header = inflater.inflate(R.layout.layout_header, null);
		View footer = inflater.inflate(R.layout.layout_footer, null);
		llLoadingFooter = (LinearLayout) footer
				.findViewById(R.id.llLoadingFooter);
		lvVideo.addHeaderView(header);
		lvVideo.addFooterView(footer);

		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		llNotInternet = (LinearLayout) findViewById(R.id.llNoInternet);

		adapter = new ItemVideoRelativeAdapterPlay(SearchResultActivity.this,
				imageLoader, options);

		// idCat = String.valueOf(application.getCatID());

		// if(idCat.equals("") || idCat.equals("0")|| idCat.equals("-1"))
		// {
		// idCat = "0";
		// }
		//
		// Debug.debug("CatId New Video : " + idCat);

		loadMore();
		lvVideo.setAdapter(adapter);

		adapter.setClickItemVideo(new IClickItemVideo() {

			@Override
			public void onclickItem(final String vid, final String linkvideo) {

				if (vid.equals("3") || vid.equals("10") || vid.equals("15")
						|| vid.equals("19")) {
					if (app.isAds()) {
						app.setAds(false);
						MobileCore.init(self, E4KidsConfig.MOBICORE,
								LOG_TYPE.DEBUG);

						MobileCore.showOfferWall(self, new CallbackResponse() {
							@Override
							public void onConfirmation(TYPE arg0) {
								Bundle bundle = new Bundle();
								bundle.putString(E4KidsConfig.KEY_INTENT_VID,
										vid);
								bundle.putString(E4KidsConfig.KEY_INTENT_LINK,
										linkvideo);

								goActivitySearch(SearchResultActivity.this,
										PlayVideoYoutbe.class, bundle);
							}
						});
					} else {
						Bundle bundle = new Bundle();
						bundle.putString(E4KidsConfig.KEY_INTENT_VID, vid);
						bundle.putString(E4KidsConfig.KEY_INTENT_LINK,
								linkvideo);

						goActivitySearch(SearchResultActivity.this,
								PlayVideoYoutbe.class, bundle);
					}
				} else {
					Bundle bundle = new Bundle();
					bundle.putString(E4KidsConfig.KEY_INTENT_VID, vid);
					bundle.putString(E4KidsConfig.KEY_INTENT_LINK, linkvideo);

					goActivitySearch(SearchResultActivity.this,
							PlayVideoYoutbe.class, bundle);
				}

			}
		});

		// lvVideo.setOnItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
		// long arg3) {
		// Intent intent = new Intent(SearchResultActivity.this,
		// PlayVideo.class);
		// startActivity(intent);
		// }
		// });

		lvVideo.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {

			}

			@Override
			public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
				if ((arg1 + arg2) == arg3 && isLoading) {
					if (page <= 5) {
						isLoading = false;
						page = page + 1;
						llLoadingFooter.setVisibility(View.VISIBLE);

						loadMore();

						Debug.debug("Page New: " + page);
					}
				}
			}
		});
	}

	private class RequestVideoNew extends BaseRequestHandler {
		public RequestVideoNew(Activity context, OnClickListener clickTry) {
			super(context, clickTry);
		}

		@Override
		public void onWait(BzydroidHttpClient arg0) {
			super.onWait(arg0);
			// llLoading.setVisibility(View.VISIBLE);
		}

		@Override
		public void onStarted(BzydroidHttpClient arg0) {
			super.onStarted(arg0);
			Debug.debug("onStarted");
		}

		@Override
		public void onSuccess(BzydroidHttpClient arg0, NetworkResponse arg1) {

			// Debug.debug("Danh sach : " + a);
			HttpJSONObjectResponse jsonObjectResponse = (HttpJSONObjectResponse) arg0
					.getResponse();
			try {
				JSONObject object = jsonObjectResponse.toJSONObject();
				//
				Debug.debug("Danh sach : " + object.toString());

				JSONObject jObjData = object
						.getJSONObject(E4KidsConfig.KEY_DATA);

				int code = jObjData.getInt(E4KidsConfig.KEY_CODE);

				if (code == 1) {
					Debug.debug("Con du lieu");

					isLoading = true;

					JSONArray jArrVideo = jObjData
							.getJSONArray(E4KidsConfig.Search.KEY_VIDEO);

					int length = jArrVideo.length();

					for (int i = 0; i < length; i++) {
						JSONObject jObj = jArrVideo.getJSONObject(i);

						InfoVideo infoVideo = parseJsonSearch(jObj);

						adapter.addData(infoVideo);
					}
					lvVideo.setVisibility(View.VISIBLE);
				} else {
					Debug.debug("Het du lieu");
					isLoading = false;
					if (adapter.getCount() <= 0) {
						tvNoData.setVisibility(View.VISIBLE);
						lvVideo.setVisibility(View.GONE);
						llLoadingFooter.setVisibility(View.GONE);
					} else {
						llLoadingFooter.setVisibility(View.GONE);
						tvNoData.setVisibility(View.GONE);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onError(BzydroidHttpClient arg0,
				BzydroidNetworkExeception arg1) {
			super.onError(arg0, arg1);
			Debug.debug("onError");

			if (!Util.isConnectingToInternet(SearchResultActivity.this)) {
				lvVideo.setVisibility(View.GONE);
				if (llLoading.getVisibility() == View.VISIBLE) {
					llLoading.setVisibility(View.GONE);
					llNotInternet.setVisibility(View.VISIBLE);
				}
			} else {
				llNotInternet.setVisibility(View.GONE);
				lvVideo.setVisibility(View.VISIBLE);
			}
		}

		@Override
		public void onFinished(BzydroidHttpClient arg0) {
			super.onFinished(arg0);
			Debug.debug("onFinished");
			llLoading.setVisibility(View.GONE);
			llLoadingFooter.setVisibility(View.GONE);
		}
	}

	private void loadMore() {
		if (requestVideoNew == null) {
			requestVideoNew = new RequestVideoNew(SearchResultActivity.this,
					clickTry);
		}
		RequestService.rqSearch(keyword, String.valueOf(page), packageName,
				requestVideoNew);

	}

	private OnClickListener clickTry = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Debug.debug("clickTry Page : " + page);

			loadMore();
		}
	};

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.iv_search:
			if (llContainEdt.getVisibility() == View.GONE) {
				llContainEdt.setVisibility(View.VISIBLE);
				ivABSearch.setVisibility(View.GONE);
				tvABTitle.setVisibility(View.GONE);
				edtABSearch.setFocusable(true);
				edtABSearch.requestFocus();
				showBoard(edtABSearch);
			}
			break;
		case R.id.iv_cancel:
			String text = edtABSearch.getText().toString().trim();
			if (!text.equals("")) {
				edtABSearch.setText("");
			} else {
				hiddenBoard(edtABSearch);
			}
			break;
		}
	}

}
